package v.show.health.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * client主动注册的时候,配置这个,基于nacos的不需要
 *
 * @author whzhang
 */
@Slf4j
public class DefaultClientProperty implements EnvironmentPostProcessor {
    public static final String SUFFIX = "/";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        Map<String, Object> map = new HashMap<>(20);
        // client http config
        String contextPath = EnvHelper.getValue(environment, "${server.servlet.context-path:}");
        if (StringUtils.hasText(contextPath)) {
            if (!contextPath.endsWith(SUFFIX)) {
                contextPath += SUFFIX;
            }
            String pathApi = contextPath + "actuator";
            log.info("spring.cloud.nacos.discovery.metadata.management.context-path :{}", pathApi);
            map.put("spring.cloud.nacos.discovery.metadata.management.context-path", pathApi);
        }

        // admin server security
        map.put("spring.boot.admin.client.username",
                EnvHelper.getValue(environment, "${health.adminUser.name:health-admin}"));
        map.put("spring.boot.admin.client.password",
                EnvHelper.getValue(environment, "${health.adminUser.password:Z4xVYlHudz32j4UU}"));

        // client security
        map.put("spring.boot.admin.client.instance.metadata.user.name",
                EnvHelper.getValue(environment, "${spring.application.name}"));
        map.put("spring.boot.admin.client.instance.metadata.user.password",
                EnvHelper.getValue(environment, "${sba.client.password:zruiBPtg5dy3vQ0L}"));

        MapPropertySource source = new MapPropertySource("DefaultClientProperty", map);
        environment.getPropertySources().addLast(source);
    }
}
